package pl.shenlon.ga.selection;

import pl.shenlon.ga.Population;
import pl.shenlon.ga.Specimen;

public class RankedSpecimenSelector extends PopulationSpecimenSelector {
	public RankedSpecimenSelector(Population population) {
		super(population);
	}

	@Override
	public Specimen[] select() {
		if (population.getScore() <= 0) {
			return population.getPopulation();
		}
		Specimen[] populationSpecimens = population.getPopulation();
		int populationSize = population.getPopulationSize();
		double sum = ((1 + populationSize) / 2.0) * populationSize;
		population.sortAscending();
		Specimen[] specimens = new Specimen[populationSize];
		for (int i = population.getElitarismRate(); i < specimens.length; i++) {
			int rand = rnd.nextInt((int) sum);
			int delta = 1 + 8 * rand;
			double x = (1 + Math.sqrt(delta)) / 2.0;
			x = Math.floor(x);
			specimens[i] = populationSpecimens[(int) x - 1];
		}
		return specimens;
	}

}